package com.gjt.http;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.CacheResponse;
import java.net.URLConnection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created with Intel IDEA.
 * CacheResponse的一个子类，绑定到一个SimpleCacheRequest 和一个 CacheControl,共享引用将数据从请求传递给响应类。如果在文件中储存响应，就需要共享文件名
 *                  除了SimpleCacheRequest对象（从中读取数据），还必须将最初的URLConnection 对象传递给构造函数，用来读取HTTP首部，可以存储这个首部以后、
 *                  获取，这个对象还记录了服务器为资源的缓存表示提供的过期时间和缓存控制策略（如果有的话）
 *
 *
 * @Auther: gjt
 * @Date: 2024/3/27 17:28
 */
public class SimpleCacheResponse extends CacheResponse {

    private final Map<String,List<String>> headers;

    private final SimpleCacheRequest request;

    private final Date expires;

    private final CachedControl control;

    public SimpleCacheResponse (SimpleCacheRequest request, URLConnection uc , CachedControl control){
        this.request = request;
        this.control = control;
        this.expires = new Date(uc.getExpiration());
        this.headers = Collections.unmodifiableMap(uc.getHeaderFields());
    }

    @Override
    public Map<String, List<String>> getHeaders() throws IOException {
        return headers;
    }

    @Override
    public InputStream getBody() throws IOException {
        return new ByteArrayInputStream(request.getData());
    }

    /**
     * 检测是否过期
     */
    public boolean isExpired(){
        Date date = new Date();
        if(control.getMax_age().before(date))return true;
        else if(expires != null && control.getsMaxage() != null){
            return expires.before(date);
        }else return  false;
    }

}
